#include "resample.h"
#include <QDebug>

Resample::Resample() {}

bool Resample::initSwrCtx(AVCodecParameters *params)
{
    if (params == nullptr){
        qDebug() << "Resample::initSwrCtx params == nullptr error";
        return false;
    }
    //设置参数并为swrCtx分配空间
    int ret = swr_alloc_set_opts2(&swrCtx,
                        &params->ch_layout,outFormat,params->sample_rate,
                        &params->ch_layout,AVSampleFormat(params->format),params->sample_rate,
                                  0,nullptr);
    if(ret < 0){
        qDebug() << "Resample::initSwrCtx(AVCodecParameters *params) error";
        return false;
    }
    //初始化
    ret = swr_init(swrCtx);
    if (ret != 0)
    {
        char buf[1024] = { 0 };
        av_strerror(ret, buf, sizeof(buf) - 1);
        qDebug() << "swr_init  failed! :" << buf;
        return false;
    }
    return true;
}

int Resample::transDataFmtRetSize(AVFrame *indata, unsigned char *data)
{
    if (indata == nullptr) {
        qDebug() << "Resample::transDataFmtRetSize indata == nullptr error";
        return 0;
    }
    if (data == nullptr)
    {
        av_frame_free(&indata);
        qDebug() << "Resample::transDataFmtRetSize data == nullptr error";
        return 0;
    }
    //重采样之后的数据存放在这里
    uint8_t *newData[1] = { 0 };
    newData[0] = data;
    //返回每个通道的采样大小
    int sampleSize = swr_convert(swrCtx,newData, indata->nb_samples,(const uint8_t**)indata->data, indata->nb_samples);
    if (sampleSize <= 0){
        qDebug() << "Resample::transDataFmtRetSize sampleSize <= 0 error";
        return sampleSize;
    }
    //音频数据大小 采样大小*通道数*位深
    int dataSize = sampleSize * indata->ch_layout.nb_channels * av_get_bytes_per_sample((AVSampleFormat)outFormat);
    return dataSize;
}
